// pulse_controlled_device.c
//
// Pulse controlled device implementation.
// Servos and motor controllers are pulse controlled devices.
//
// Author: egor.zaitsev@tut.by

#include "pulse_controlled_device.h"

void InitDevice(PulseControlledDevice_t *device,
                ControlValue_t initialValue, ControlValue_t minValue, ControlValue_t maxValue,
                Pulse_t period,
                Pulse_t minPulse, Pulse_t maxPulse)
{
    ASSERT(minValue <= maxValue);

    device->minValue = minValue;
    device->maxValue = maxValue;

    device->period = period;

    ASSERT(minPulse <= maxPulse);
    ASSERT((minPulse <= period) && (maxPulse <= period));

    device->minPulse = minPulse;
    device->maxPulse = maxPulse;

    SetValue(device, initialValue);
}

ControlValue_t GetValue(PulseControlledDevice_t *device)
{
    return device->currentValue;
}

void SetValue(PulseControlledDevice_t *device, ControlValue_t value)
{
    ASSERT((device->minValue <= value) && (value <= device->maxValue));
    
    device->currentValue = value;
    
    device->currentPulse = device->minPulse +
                          (device->maxPulse - device->minPulse) * (Pulse_t)(device->currentValue - device->minValue) / (Pulse_t)(device->maxValue - device->minValue);
}
